package com.markhsiu.store.disk;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *  单线程写
 * 
 * @author Mark Hsiu
 */
class MapFileWrite extends MapFile{
	
 
	private MappedByteBuffer master;
 
    private AtomicInteger position = new AtomicInteger(0);
     
	public MapFileWrite(File file) {
			 super(file);
			 try {
				 master = channel.map(MapMode.READ_WRITE, headLen(), size());	
			} catch (IOException e) {
				e.printStackTrace();
			}	
	}

 
	//tryLock 调用了 143k
	public void write(ByteBuffer writeUsed, byte[] bytes, int offset, int length) {	 
		int pos = position.getAndAdd(length);
		writeUsed.position(pos);
		writeUsed.put(bytes, offset, length);
		
//		int index = pos % num;
//		synchronized (locks[index]) {		   
//			  writeMuti[index].position(pos);
//			  writeMuti[index].put(bytes, offset, length);
//		}
		

//		if(LOCK.tryLock()){
//			mapBuffer.put(bytes, offset, length);
//		} else {
//			System.out.println("tryLock ... ");
//		}
	}
	
 
	public int position(){
		return position.get();
	}
	
	public ByteBuffer duplicate(){
		return master.duplicate();
	}
	 
	
	public void flush() throws IOException {
		// 不force的话，内存产生大量的垃圾page file
		channel.force(false);
	}

	 

	 
}
